package com.caifu.controller;

import com.caifu.bean.Result;
import com.caifu.bean.ResultUtil;
import com.caifu.pojo.SysUser;
import net.sf.json.JSONObject;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.authz.UnauthenticatedException;
import org.apache.shiro.authz.UnauthorizedException;
import org.apache.shiro.session.ExpiredSessionException;
import org.apache.shiro.subject.Subject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * @Author:debug
 * @Date: 2019/7/30 12:23
 **/
@Controller
@ApiIgnore
public abstract class AbstractController {

//    @Autowired
//    private SysUserTokenService tokenService;

    //日志
    protected Logger log= LoggerFactory.getLogger(getClass());

    //获取当前登录用户的详情
    protected SysUser getUser(){
        SysUser user= (SysUser) SecurityUtils.getSubject().getPrincipal();
        if(user != null) {
            SysUser sessionUser = (SysUser) SecurityUtils.getSubject()
                    .getSession().getAttribute("user");
            if (null != sessionUser) {
                user.setCurrentPensionNo(sessionUser.getCurrentPensionNo());
            }
            user.setPassword("");
            user.setPaw("");
            user.setSalt("");
        }

        return user;
    }



    /**
     * 判断当前登录用户（主体）是否有 指定的权限
     * @param permission 指定的权限
     * @return
     */
    public Boolean hasPermission(String permission){
        Subject subject= SecurityUtils.getSubject();
        return (subject!=null && subject.isPermitted(permission))? true : false;
    }

    /**
     * 登录认证异常
     *
     * @param request
     * @param response
     * @return
     */
    @ExceptionHandler({ UnauthenticatedException.class, AuthenticationException.class })
    public void authenticationException(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("status", "-1000");
        map.put("message", "未登录");
        //writeJson(map, response);
        //ShiroUtil.logout();
        //return "redirect:http://192.168.1.180:6060/SilverMountain/login";
        response.sendRedirect(request.getContextPath()+"/login");
    }

    /**
     * 权限异常
     *
     */
    @ExceptionHandler({ UnauthorizedException.class, AuthorizationException.class })
    public String authorizationException(HttpServletRequest request, HttpServletResponse response) {
        Map<String, Object> map = new HashMap<>();
        map.put("status", "-1001");
        map.put("message", "无权限");
        //writeJson(map, response);
        return "redirect:login?type=1";
    }

    /**
     * 功能描述: session失效
     * @Param:  [request, response]
     * @Author: szt
     * @Date:   2020/10/10
     */
    @ExceptionHandler(value=ExpiredSessionException.class)
    public String expiredSessionException(ExpiredSessionException e) {
        return "redirect:login?type=1";
    }

    private void writeJson(Map<String, Object> map, HttpServletResponse response) {
        PrintWriter out = null;
        try {
            JSONObject json = JSONObject.fromObject(map);
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/json; charset=utf-8");
            out = response.getWriter();

            out.write(json.toString());
        } catch (IOException e) {
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }


    protected String getUserName(){
        SysUser user = getUser();
        if(user != null){
            return user.getUserName();
        }else{
            return null;
        }
    }
    protected String getLoginName(){
        SysUser user = getUser();
        if(user != null){
            return user.getLoginName();
        }else{
            return null;
        }
    }
    protected int getUserNo(){
        SysUser user = getUser();
        if(user != null){
            return user.getUserNo();
        }else{
            return 0;
        }
    }

    /**
     * 返回成功
     */
    protected Result success(Integer code, String msg) {
        return ResultUtil.success(code, msg);
    }

    /**
     * 返回成功
     */
    protected Result success(Integer code, String msg, Object data) {
        return ResultUtil.success(code, msg, data);
    }

    /**
     * 返回失败消息
     */
    protected Result error(Integer code, String message) {
        return ResultUtil.error(code, message);
    }

}